<template>
  <el-dialog :title="form.id ? '编辑权限点' : '新增权限点'" :visible="dialogVisible" width="650px" @close="close">
    <el-form :model="form" :rules="rules" ref="form" label-width="100px">
      <el-form-item label="权限名称" prop="name">
        <el-input v-model="form.name" size="small" style="width: 450px"></el-input>
      </el-form-item>
      <el-form-item label="权限标识" prop="code">
        <el-input v-model="form.code" size="small" style="width: 450px"></el-input>
      </el-form-item>
      <el-form-item label="权限描述" prop="description">
        <el-input v-model="form.description" size="small" style="width: 450px"></el-input>
      </el-form-item>
      <el-form-item label="开启" prop="enVisible">
        <el-switch
            v-model="form.enVisible"
            active-value="1"
            inactive-value="0">
          </el-switch>
      </el-form-item>
    </el-form>
    <div class="dialog-footer">
      <el-button type="primary" size="small" @click="confirm">确 定</el-button>
      <el-button size="small" @click="close">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { addPermission, editPermission } from '@/api/permission'
  export default {
    name: 'AddPermission',
    props: ['dialogVisible'],
    data() {
      return {
        form: {
          name: '',
          code: '',
          description: '',
          enVisible: '0',
          type: 1,
          pid: 0
        },
        rules: {
          name: [{ required: true, message: '权限名称不能为空', trigger: 'blur' }],
          code: [{ required: true, message: '权限标识不能为空', trigger: 'blur' }]
        }
      }
    },
    methods: {
      confirm() {
        this.$refs.form.validate(async valid => {
          if (valid) {
            // 通过是否有权限点id判断是新增权限点还是修改权限点详情
            if(this.form.id) {
              // 调用修改权限点详情的请求接口
              await editPermission(this.form)
              this.$message.success('修改权限点成功')
              // 通知父组件重新获取权限列表，渲染表格页面
              this.$emit('getPermissionList')
              // 重置表单，关闭弹层
              this.close()
            } else {
              // 调用新增员工请求接口
              await addPermission(this.form)
              this.$message.success('新增成功')
              // 通知父组件重新获取权限列表，渲染表格页面
              this.$emit('getPermissionList')
              // 重置表单，关闭弹层
              this.close()
            }
          }
        })
      },
      close() {
        // 重置表单内绑定的数据为初始值，以及重置校验
        this.$refs.form.resetFields()
        // 重置整个表单的数据为初始值
        this.form = {
          name: '',
          code: '',
          description: '',
          enVisible: '0',
          type: 1,
          pid: 0
        },
        // 关闭弹层
        this.$emit('update:dialogVisible', false)
      }
    }
  }
</script>

<style>
</style>